﻿using Sprout.Cache.Redis;
using Sprout.Schedule.Dtos;
using Sprout.Schedule.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Sprout.Core.Extensions;
using Sprout.Core.Utils;
using System.Linq;
using Sprout.Schedule.Daos;
using Microsoft.Extensions.Logging;
using Sprout.Repository;
using Sprout.Core;
using Sprout.Core.Paging;

namespace Sprout.Schedule.Services
{
    public class TaskLogService : ITaskLogService
    {
        const string taskLogRedisKey = "Schedule:TaskLog";

        Lazy<ITaskLogDao> taskLogDao = ServiceLocator.GetLazyService<ITaskLogDao>();
        //ILogger _logger;
        //public TaskLogService(ILoggerFactory loggerFactory)
        //{
        //    _logger = loggerFactory.CreateLogger("调度中心日志入库");
        //}


        /// <summary>
        /// 任务日志存库
        /// </summary>
        /// <param name="pageSize"></param>
        /// <returns>写入的行数</returns>
        public async Task<int> Insert(int pageSize)
        {
            int count = 0;
            while (true)
            {
                var logs = await RedisService.LRangeAsync<TaskLog>(taskLogRedisKey, 0, pageSize);

                if (logs != null && logs.Count() > 0)
                {
                    count = logs.Count();
                    await taskLogDao.Value.InsertAsync(logs);
                    //删除已经存库的日志
                    await RedisService.LTrimAsync(taskLogRedisKey, logs.Count(), -1);
                    if (logs.Count() < pageSize)
                    {
                        break;
                    }
                }
            }
            return count;
        }

        /// <summary>
        /// 分页查询日志记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagedList<TaskLog>> GetPaging(TaskLogQuery query)
        {
            return await taskLogDao.Value.GetPagingAsync(query);
        }
        /// <summary>
        /// 删除日志
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<int> Delete(TaskLog dto)
        {
            return await taskLogDao.Value.DeleteAsync(dto);
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="content"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public async Task LogAsync(long taskId, string content, Exception exception = null)
        {
            //临时写入redis，使用计划任务进行将redis中的日志写入到数据库
            await RedisService.RPushAsync(taskLogRedisKey, new TaskLog()
            {
                TaskId = taskId,
                Content = content,
                Exception = exception?.StackTrace,
                CreateTime = DateTime.Now
            });
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="content"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public void Log(long taskId, string content, Exception exception = null)
        {
            //临时写入redis，使用计划任务进行将redis中的日志写入到数据库
            RedisService.RPush(taskLogRedisKey, new TaskLog()
            {
                TaskId = taskId,
                Content = content,
                Exception = exception?.StackTrace,
                CreateTime = DateTime.Now
            });
        }
    }
}
